package com.zhanghe.study.demo.es;

import com.google.gson.Gson;
import com.zhanghe.study.demo.es.model.AdCampaign;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/**
 * @author zh
 * @date 2022/3/31 17:21
 */
public class Hadoop2EsMapper extends Mapper<LongWritable, Text, NullWritable, Text> {

    private final String csvSplitBy = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)(?!([^\\[]*]))";

    Gson gson = new Gson();

    Text v = new Text();

    @Override
    public void run(Context context) throws IOException, InterruptedException {
        super.run(context);
    }

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        System.out.println("执行");
        v.set(csvToJson(value));
        context.write(NullWritable.get(), v);
    }

    private String csvToJson(Text value){
        String[] fields = value.toString().split(csvSplitBy);

        AdCampaign adCampaign = new AdCampaign();
        adCampaign.setId(Long.parseLong(fields[0]));
        adCampaign.setName(fields[1]);
        adCampaign.setStart_time(Long.parseLong(fields[2]));
        adCampaign.setEnd_time(Long.parseLong(fields[3]));
        adCampaign.setFrequency(Integer.parseInt(fields[4]));
        adCampaign.setFrequency_interval_type(Integer.parseInt(fields[5]));
        adCampaign.setTime_slots(fields[6]);
        adCampaign.setPriority(Integer.parseInt(fields[7]));
        adCampaign.setLocation_package_list(fields[8]);
        adCampaign.setTrack_frequency(Integer.parseInt(fields[9]));
        adCampaign.setAllow_over(Integer.parseInt(fields[10]));
        adCampaign.setCreative_mode(Integer.parseInt(fields[11]));
        adCampaign.setAd_brand_id(Integer.parseInt(fields[12]));
        adCampaign.setAd_owner_id(Long.parseLong(fields[13]));
        adCampaign.setDevice_min_size(Integer.parseInt(fields[14]));
        adCampaign.setDevice_max_size(Integer.parseInt(fields[15]));
        adCampaign.setTa_optimize(Integer.parseInt(fields[16]));
        adCampaign.setTarget_group_ids(fields[17]);
        adCampaign.setTarget_group_rule(Integer.parseInt(fields[18]));
        adCampaign.setTarget_group_provider(Integer.parseInt(fields[19]));
        adCampaign.setAd_plan_id(Integer.parseInt(fields[20]));
        adCampaign.setAppend_type(Integer.parseInt(fields[21]));
        adCampaign.setAppend_camps(fields[22]);
        adCampaign.setAdx_camp_id(Integer.parseInt(fields[23]));
        adCampaign.setSupport_mid_monitor(Integer.parseInt(fields[24]));
        adCampaign.setSupport_end_monitor(Integer.parseInt(fields[25]));
        adCampaign.setSupport_click_monitor(Integer.parseInt(fields[26]));
        adCampaign.setMutex_brands(fields[27]);

        String result = gson.toJson(adCampaign);
        System.out.println(result);

        return result;
    }
}
